<template>
	<a-form-item>
		<a-button type="primary" @click="addBlank">新增填空位</a-button>
	</a-form-item>

	<a-form-item
		v-for="(blank, blankIndex) in blankLocal"
		:key="blankIndex"
		:label="`填空位 ${blankIndex + 1} 答案（任意答案匹配即算正确）`"
	>
		<a-form-item v-for="(option, optionIndex) in blank" :key="optionIndex">
			<a-row :gutter="16" justify="space-around" align="middle">
				<a-col :span="16">
					<a-input v-model:value="blank[optionIndex]" placeholder="请输入答案" />
				</a-col>
				<a-col :span="8">
					<a-space>
						<a-button danger @click="removeOption(blankIndex, optionIndex)">删除</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form-item>
		<a-form-item>
			<a-button type="primary" @click="addOption(blankIndex)" danger> 新增答案项 </a-button>
		</a-form-item>
	</a-form-item>
</template>

<script setup>
	const props = defineProps({
		answer: {
			type: String,
			required: true
		}
	})
	const addBlank = () => {
		blankLocal.value.push([''])
	}
	const addOption = (blankIndex) => {
		blankLocal.value[blankIndex].push('')
	}
	const removeOption = (blankIndex, optionIndex) => {
		blankLocal.value[blankIndex].splice(optionIndex, 1)
		if (blankLocal.value[blankIndex].length === 0) {
			blankLocal.value.splice(blankIndex, 1)
		}
	}

	const blankLocal = ref([['答案1-1', '答案1-2'], ['答案2-1']])

	const emit = defineEmits(['updateAnswer', 'updateIssueOption'])

	watch(
		blankLocal,
		(newVal) => {
			emit('updateAnswer', JSON.stringify(newVal))
			emit('updateIssueOption', newVal.length)
		},
		{ deep: true }
	)

	// 模拟 created 生命周期
	onBeforeMount(() => {
		try {
			const data = JSON.parse(props.answer)
			if (data && Array.isArray(data)) {
				for (let i = 0; i < data.length; i++) {
					if (!Array.isArray(data[i])) {
						return
					}
				}
				blankLocal.value = data
			}
		} catch (e) {
			/* empty */
		}
	})
</script>

<style scoped></style>
